<?php

App::import('Sanitize');

class SubjectsController extends AppController {

    var $name = 'Subjects';
    var $components = array('RequestHandler', 'Access');
    var $paginate = array(
        'limit' => '10',
        'order' => array('Subject.subject' => 'desc')
    );
    var $uses = array('Tag', 'Adjective', 'Subject', 'Credit', 'UserCredit', 'FlaggedSubject');

    function beforeFilter() {


        $this->Auth->loginRedirect = array('controller' => 'Dashboard', 'action' => 'index');
        $this->Auth->allow('check', 'synonyms');
    }

    function admin_index() {

        if (!$this->Access->check('Subject', 'read')) {
            $this->Session->setFlash(__("You don't have permissions to View this content"));
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (isset($this->params['named']['status'])) {
            $this->paginate = array(
                'limit' => '10',
                'order' => array('Subject.created' => 'desc'),
                'conditions' => array('Subject.status' => $this->params['named']['status'])
            );
        }
        $data = $this->paginate('Subject');
        $adjectives = '';
        $taglist = '';
        $i = 0;

        /*         * ********  Loop through the fetched data to get Formated Taglist and Adjectives      ****** */

        foreach ($data as $value) {
            $adj_ids = explode(',', $value['Subject']['adjective_ids']);
            $tag_ids = explode(',', $value['Subject']['tag_ids']);

            /*             * ************************* This loop will get you the Adjectives from adjective_ids     ************************ */
            foreach ($adj_ids as $id) {
                $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id =' => $id)));
                $adjectives = $adjectives . ',' . $adj['Adjective']['title'];
            }


            /*             * ************** 
             * This loop will get all the formated tags for a particular record.
             *  Functions used : 
             *                  get_parent_list($tid):accepts tag_id as input. this will return an array with parent ids and parent titles.
             *                  formated_tags($tag_arr,$saparator):First argument is the tag_array returned from get_parent_list.Second parameter is optional. This will be used as to format taglist.
             * 
             * *************** */
            foreach ($tag_ids as $tid) {
                $tag_arr = $this->get_parent_list($tid);
                $taglist = $this->formated_tags($tag_arr, '>');
            }
            $data[$i]['Subject']['adjective_ids'] = substr($adjectives, 1);
            $data[$i]['Subject']['tag_ids'] = $taglist;
            $i++;
            $adjectives = '';
            //$tags='';
        }

        /*         * **********  Loop to get Taglist and Adjectives ENDS     ******************** */

        //debug($data);
        $this->set('Subjects', $data);
    }

    function admin_approve($id=null) {
        if (!$this->Access->check('User', 'read')) {
            $this->Session->setFlash('You dont have permissions to View this content');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (!empty($id) || isset($this->data)) {

            if (empty($this->data)) {
                $data = $this->Subject->find('first', array('conditions' => array('Subject.id =' => $id, 'Subject.status =' => '0'), 'recursive' => '2'));
                if (!$data) {
                    $this->Session->setFlash('Subject Already approved.Cant approve again ');
                    $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
                }
                $this->admin_edit($id);
                $credits = $this->Credit->find('all');
                $urating = $this->Subject->query("SELECT subject_rates.rating, user_id FROM `subject_rates` where subject_id='$id'");
                $this->set('credits', $credits);
            } else {
                $redirect = true;                             //We will set $redirect to true so that admin_edit does not redirect as we want the control back for further process 
                $this->admin_edit($this->data, $redirect);
                $this->saveCredit($this->data);
                $update = mysql_query("Update `subject` set status='1',`approved_by`='" . $_SESSION['Auth']['User']['id'] . "',`approved_on`=NOW() where subject.id='" . $this->data['Subject']['id'] . "'");
                $this->Session->setFlash('Subject Approved.');

                $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => '0'));


                //debug($this->data);
            }
        } else {
            $this->Session->setFlash('Subject not available ');
            $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
        }
    }

    function admin_add() {
        if (!$this->Access->check('Subject', 'create')) {
            $this->Session->setFlash("You can't add new subjects");
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (isset($this->data)) {

            $tags = array();

            if (isset($_POST['tag_ids'])) {
                $tags = $_POST['tag_ids'];
            }
            //if(!empty($_POST['data']['Subject']['tag_ids'])){array_push($tags, $_POST['data']['Subject']['tag_ids']);}
            $uniquetags = array_unique($tags);

            $tag_ids = implode(',', $uniquetags);
            $tag_ids = ltrim($tag_ids, ',');
            $this->data['Subject']['tag_ids'] = $tag_ids;
            //debug($tag_ids);debug($uniquetags);die();            
            //print_r($_POST);
            //debug($tag_ids);
            //debug($this->data);die();




            if ($this->data['Subject']['image']['error'] == '0') {
                $ext = pathinfo(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['image']['name']);
                if ($this->check_image_extension($ext['extension'])) {
                    $image_name = uniqid($this->data['Subject']['subject'], true) . '.' . $ext['extension'];
                    if (!file_exists(WWW_ROOT . 'img/uploads/Subjects/' . $image_name)) {
                        move_uploaded_file($this->data['Subject']['image']['tmp_name'], WWW_ROOT . 'img/uploads/Subjects/' . $image_name);
                    }

                    /*   if ($this->Subject->validates(array('fieldlist' => array('image')))) {
                      if (!is_dir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'])) {

                      mkdir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject']);

                      chmod(WWW_ROOT . 'img/uploads/Subjects/'. $this->data['Subject']['subject'],'0777');
                      $path = WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'];
                      } elseif (is_dir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'])) {
                      if (!empty($this->data['Subject']['image'])) {

                      move_uploaded_file($this->data['Subject']['image']['tmp_name'], WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'] . '/' . $this->data['Subject']['image']['name']);
                      } else {
                      $this->Session->setFlash('Somthing went wrong uploading image');
                      }
                      }
                      } */


                    $this->data['Subject']['image'] = $image_name;
                } else {
                    $this->data['Subject']['image'] = '';
                }
            } else {
                $this->data['Subject']['image'] = '';
            }
            $this->data['Subject']['user_id'] = $_SESSION['Auth']['User']['id'];
            $this->data['Subject']['desc'] = strtolower($this->data['Subject']['desc']);
            //$this->data = Sanitize::clean($this->data, array('encode' => false));

            if ($this->Subject->saveAll($this->data, array('validate' => 'first'))) {
                $this->data['SubjectRate']['subject_id'] = $this->Subject->id;
                $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                $this->data['SubjectRate']['rating'] = $_POST['rating'];
                $this->Subject->SubjectRate->save($this->data, array('validate' => 'only'));
                $this->Session->setFlash('Subject Saved');
                $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => '0'));
            }
        }
    }

    function admin_edit($id=null, $redirect=null) {                      //We have introduced second argument to override the default redirect on successfull save. When set to true this method will not redirect.
        if (!$this->Access->check('Subject', 'update')) {
            $this->Session->setFlash('Permission denied. Please contact your Administrator for more permissions');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if ($id) {
            if (empty($this->data)) {

                $this->data = $this->Subject->read(null, $id);
                $synonymlist = $this->synonymlist($id);

                $this->set('synonymlist', $synonymlist);
                if (($this->Access->check('User', 'update')) || ($this->data['Subject']['user_id'] == $_SESSION['Auth']['User']['id'] && $this->data['Subject']['status'] == '0')) {




                    $tags = array();
                    if (!empty($this->data['Subject']['adjective_ids'])) {
                        $adjectivelist = $this->adjectivelist($this->data['Subject']['adjective_ids']);
                        $this->set('adjectivelist', $adjectivelist);
                    }
                    $tag_ids = explode(',', $this->data['Subject']['tag_ids']);
                    foreach ($tag_ids as $tid) {
                        $tag_arr = $this->get_parent_list($tid);
                        $taglist = $this->formated_tags($tag_arr, '>');
                        $tag_arr = array('tag_id' => $tid, 'tag' => $taglist);
                        array_push($tags, $tag_arr);
                    }

                    $this->data['Subject']['taglist'] = $tags;

                    $this->set('id', $id);
                    /*                     * *****Prepopulate Adjective list******** */
                } else {
                    $this->Session->setFlash('You can only Edit your own submitted Subjects');
                    $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => '0'));
                }
            } else {
                //debug($this->data);die();
                if (!empty($this->data['Subject']['subject_ids']) || !empty($this->data['Subject']['old_subject_ids'])) {
                    $this->set_base_subject($this->data);
                }
                $tag_ids = null;
                $this->Subject->id = $this->data['Subject']['id'];
                if (isset($_POST['tag_ids'])) {
                    $tags = $_POST['tag_ids'];
                    //if(!empty($_POST['data']['Subject']['tag_ids'])){array_push($tags, $_POST['data']['Subject']['tag_ids']);}
                    $uniquetags = array_unique($tags);
                    //debug($uniquetags);die();
                    $tag_ids = implode(',', $uniquetags);
                    $tag_ids = ltrim($tag_ids, ',');
                }
                $this->data['Subject']['tag_ids'] = $tag_ids;

//debug($tag_ids);debug($uniquetags);die();  
                if (isset($this->data['Subject']['image'])) {
                    if ($this->data['Subject']['image']['error'] != '0') {
                        $this->data['Subject']['image'] = '';
                    } else {
                        $ext = pathinfo(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['image']['name']);
                        if ($this->check_image_extension($ext['extension'])) {
                            $image_name = uniqid($this->data['Subject']['subject'], true) . '.' . $ext['extension'];
                            $filename = WWW_ROOT . 'img/uploads/Subjects/' . $image_name;
                            if (!file_exists(WWW_ROOT . 'img/uploads/Subjects/' . $image_name)) {
                                move_uploaded_file($this->data['Subject']['image']['tmp_name'], WWW_ROOT . 'img/uploads/Subjects/' . $image_name);
                            }

                            /*   if ($this->Subject->validates(array('fieldlist' => array('image')))) {
                              if (!is_dir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'])) {

                              mkdir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject']);

                              chmod(WWW_ROOT . 'img/uploads/Subjects/'. $this->data['Subject']['subject'],'0777');
                              $path = WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'];
                              } elseif (is_dir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'])) {
                              if (!empty($this->data['Subject']['image'])) {

                              move_uploaded_file($this->data['Subject']['image']['tmp_name'], WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'] . '/' . $this->data['Subject']['image']['name']);
                              } else {
                              $this->Session->setFlash('Somthing went wrong uploading image');
                              }
                              }
                              } */
                            $this->data['Subject']['image'] = $image_name;
                        } else {
                            $this->data['Subject']['image'] = null;
                        }
                    }
                }
                $this->data['Subject']['desc'] = strtolower($this->data['Subject']['desc']);  // Convert specifier to lowercase
                if (isset($_POST['rating_id'])) {
                    if ($this->Subject->saveAll($this->data, array('validate' => 'first'))) {
                        $this->data['SubjectRate']['subject_id'] = $this->Subject->id;
                        $this->data['SubjectRate']['id'] = $_POST['rating_id'];
                        $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                        $this->data['SubjectRate']['rating'] = $_POST['rating'];
                        $this->Subject->SubjectRate->save($this->data);
                        $this->Session->setFlash('Subject Saved');

                        $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => $this->data['Subject']['status']));
                    }
                } else {


                    $this->Subject->set($this->data);
                    //debug($this->data);die();
                    $this->Subject->save($this->data, array('validate' => false));     //dont validate on edit
//debug($this->data);die();

                    if (!$redirect) {
                        $this->Session->setFlash('Subject Updated ');
                        $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => $this->data['Subject']['status']));
                    }
                }
            }
        } else {
            $this->Session->setFlash('Subject not available ');
            $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
        }
    }

    function admin_view($id=null) {

        $adjectives = '';
        $taglist = '';
        $tags = array();
        $i = 0;
        $data = $this->Subject->find('first', array('conditions' => array('Subject.id =' => $id)), array('resursive' => '2'));


        /*         * ********  Loop through the fetched data to get Formated Taglist and Adjectives      ****** */
        //debug($data);
        //echo "<pre>";print_r($value);echo "</pre>";
        $adj_ids = explode(',', @$data['Subject']['adjective_ids']);
        $tag_ids = explode(',', @$data['Subject']['tag_ids']);

        /*         * ************************* This loop will get you the Adjectives from adjective_ids     ************************ */
        foreach ($adj_ids as $aid) {
            $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id =' => $aid)));
            $adjectives = $adjectives . ',' . $adj['Adjective']['title'];
        }


        /*         * ************** 
         * This loop will get all the formated tags for a particular record.
         *  Functions used : 
         *                  get_parent_list($tid):accepts tag_id as input. this will return an array with parent ids and parent titles.
         *                  formated_tags($tag_arr,$saparator):First argument is the tag_array returned from get_parent_list.Second parameter is optional. This will be used as to format taglist.
         * 
         * *************** */
        foreach ($tag_ids as $tid) {
            $tag_arr = $this->get_parent_list($tid);
            $taglist = $this->formated_tags($tag_arr, '>');
            $tag_arr = array('tag_id' => $tid, 'tag' => $taglist);
            array_push($tags, $tag_arr);
        }
        $data['Subject']['adjective_ids'] = substr($adjectives, 1);
        $data['Subject']['tag_ids'] = $tags;
        $i++;
        $adjectives = '';
        $tags = array();


        /*         * **********  Loop to get Taglist and Adjectives ENDS     ******************** */

        //debug($data);
        $this->set('subjects', $data);
        $lastRated = $this->Subject->SubjectRate->find('first', array(
            'conditions' => array(
                'SubjectRate.subject_id' => $id,
                'SubjectRate.user_id' => $_SESSION['Auth']['User']['id']
            ),
            'order' => 'SubjectRate.created desc',
            'limit' => '1'
                )
        );
        $this->set('lastrated', $lastRated);
    }

    function admin_delete($id=null) {
        if (!$this->Access->check('Subject', 'delete')) {
            $this->Session->setFlash('Permission denied. Please contact your Administrator for more permissions');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (!$id) {
            $this->Session->setFlash("Invalid Link");
            $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
        }
        $subject = $this->Subject->find('first', array('conditions' => array('Subject.id =' => $id)));
        //debug($categorydata);die();//$foldername=$categorydata['']
        if (!empty($subject)) {
            $dir = WWW_ROOT . 'img/uploads/Subjects/' . $subject['Subject']['image'];
            if ($this->Subject->delete($id)) {
                $folder = new File($dir);
                $folder->delete();
                $this->Session->setFlash("Subject deleted");
                $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => $this->params['named']['status']));
            }
        } else { /*         * ** In case category not found.Redirect with error message ***** */
            $this->Session->setFlash('Subject Not found.');
            $this->redirect(array('controller' => 'Subject', 'action' => 'index', 'status' => $this->params['named']['status']));
        }
    }

    function admin_flagged() {
        $this->paginate = array('limit' => '10');

        $data = $this->paginate('FlaggedSubject');

        $this->set('subjects', $data);
    }

    function admin_delete_flagged($id=null) {
        if ($id) {
            if ($this->FlaggedSubject->delete($id)) {
                $this->Session->setFlash('Successfully deleted');
                $this->redirect(array('action' => 'admin_flagged'));
            }
        } else {
            $this->redirect(array('controller' => 'Subejcts', 'action' => 'admin_flagged'));
        }
    }

    function admin_rate() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);

            $this->autoRender = false;
            if (isset($_POST['id'])) {
                $this->data['SubjectRate']['subject_id'] = $_POST['id'];
                $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                $this->data['SubjectRate']['rating'] = $_POST['rating'];

                if ($this->Subject->SubjectRate->save($this->data)) {
                    $data = mysql_query("SELECT MAX(balance) as balance FROM user_credits where user_id='" . $_SESSION['Auth']['User']['id'] . "'");
                    $row = mysql_fetch_array($data);
                    $sql = mysql_query("INSERT into user_credits (`subject_id`,`credit_id`,`user_id`,`credit`,`balance`,`created`)
                                         VALUES('" . $_POST['id'] . "','1','" . $_SESSION['Auth']['User']['id'] . "','1','" . ($row['balance'] + 1) . "',NOW())");
                    $this->Session->setFlash('Thanks for rating');
                }
            }
        }
    }

    /*     * ****************************************************************   Custom Functions Starts           *********************************************************** */

    /*     * **************** This function will return the adjectives to add and edit VIEWS. To be called from autocomplete widget *********************** */

    function admin_adjectives() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $adjectives = $this->Adjective->find('all', array('conditions' => array('Adjective.title LIKE' => '%' . $_GET['q'] . '%'), 'limit' => '10'));
            $i = 0;
            foreach ($adjectives as $adjective) {
                $response[$i]['id'] = $adjective['Adjective']['id'];
                $response[$i]['name'] = "" . $adjective['Adjective']['title'] . "";
                $i++;
            }
            if (isset($_GET["callback"])) {
                $response = $_GET["callback"] . "(" . $response . ")";
            }

            $response = json_encode($response);
            echo $response;
        }
    }

    /*     * ************************** Adjective function ends  *********************************** */

    function admin_synonyms() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $subjectlist = array();
            //echo $_POST['search'];
            $data = mysql_query("SELECT `subject`,`desc` from `subject` where `subject` LIKE '%" . $_GET['search'] . "%' || `desc` LIKE '%" . $_GET['search'] . "%'") or die(mysql_error());
            while ($row = mysql_fetch_array($data)) {
                if(!empty($row['desc'])){
                $subjectlist[] = $row['subject'] . " (" . $row['desc'] . ")";    
                $subjectlist[] = $row['subject'] . " " . $row['desc'];
                }else{
                    $subjectlist[] = $row['subject'];
                }
                   
                
                
            }
            //$data=$this->Subject->find('all',array('conditions'=>array('Subject.subject LIKE'=>'%'.$_GET['search'].'%')));
            // print_r($subjectlist);
           
//$_GET['offset']=0;
                    //echo "<pre>";
            //print_r($subjectlist);
            
                    $i = 0;
                    $offset=0;
                    $response=array();
            $result = $this->initialize_curl($response,$_GET['search'], $offset, $i,$subjectlist);


//            foreach ($result->query->search as $subject) {
//                if (!in_array($subject->title, $subjectlist)) {
//                    $response[$i]['id'] = $subject->title;
//                    $response[$i]['name'] = $subject->title;
//                    $i++;
//                } else if ($i == '51') {
//                    break;
//                } else {
//                    continue;
//                }
//            }

            $response = json_encode($result);
            echo $response;


//
//echo "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&limit=20&search=".$_POST['search'];
//            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject LIKE' => '%' . $_GET['q'] . '%'), 'limit' => '10'));
//            $i = 0;
//            foreach ($subjects as $subject) {
//                $response[$i]['id'] = $subject['Subject']['id'];
//                $response[$i]['name'] = "" . $subject['Subject']['subject'] . "";
//                $i++;
//            }
//            if (isset($_GET["callback"])) {
//                $response = $_GET["callback"] . "(" . $response . ")";
//            }
//
//            $response = json_encode($response);
//            echo $response;
        }
    }

//    function admin_synonymsbackup() {
//        if ($this->RequestHandler->isAjax()) {
//            Configure::write('debug', 0);
//            $this->autoRender = false;
//            $response = array();
//            $subjectlist=array();
//            //echo $_POST['search'];
//       
////
////echo "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&limit=20&search=".$_POST['search'];
//
//            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject LIKE' => '%' . $_GET['q'] . '%'), 'limit' => '10'));
//            $i = 0;
//            foreach ($subjects as $subject) {
//                $response[$i]['id'] = $subject['Subject']['id'];
//                $response[$i]['name'] = "" . $subject['Subject']['subject'] . "";
//                $i++;
//            }
//            if (isset($_GET["callback"])) {
//                $response = $_GET["callback"] . "(" . $response . ")";
//            }
//
//            $response = json_encode($response);
//            echo $response;
//        }
//    }
//    
//
    /*     * ************************** Tag function is called from edit and add. Called in Option tree  widget. ********************************************* */

    function admin_tags() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $response = array();
            if (!isset($_GET['id'])) {
                $_GET['id'] = '2';
            }
            $this->autoRender = false;
            if (isset($_GET['id']) && $_GET['id'] != '0') {
                $tags = $this->Tag->find('all', array('conditions' => array('Tag.parent_id =' => $_GET['id'], 'Tag.type !=' => 'attribute'), 'order' => 'Tag.position asc'));
            }
            if (!empty($tags)) {
                $response['0'] = "select Tag";
            }
            $i = 0;

            foreach ($tags as $tag) {
                $response[$tag['Tag']['id']] = "" . $tag['Tag']['title'] . "";
                $i++;
            }
            $response = json_encode($response);
            echo $response;
        }
    }

    /*     * ************ Tag function ends************ */

    function get_parent_list($id, $result_arr=array()) {
        $tag = $this->Tag->find('first', array('conditions' => array('Tag.id =' => $id)));
        $result_arr[] = array('id' => $tag['Tag']['parent_id'], 'title' => $tag['Tag']['title']);

        if ($tag['Tag']['level'] > '2') {
            return $this->get_parent_list($tag['Tag']['parent_id'], $result_arr);
        }
        return $result_arr;
    }

    function formated_tags($title_arr, $saparater='>') {
        $titles = '';
        $title_arr = array_reverse($title_arr);
        foreach ($title_arr as $title) {

            $titles.=$saparater . $title['title'];
        }
        return substr($titles, strlen($saparater));
    }

    /*     * ******************* Function  to delete image while editing subject************************* */

    function admin_delete_image($id=null) {
        if (!empty($id)) {

            $query = mysql_query("UPDATE `subject` set `image`='' WHERE id='" . $id . "'");
            $data = $this->Subject->find('first', array('conditiond' => array('Subject.id =' => $id)));
            $dir = WWW_ROOT . 'img/uploads/Subjects/' . $data['Subject']['subject'] . '/' . $data['Subject']['image'];
            $file = new File($dir);
            if ($query) {
                if ($file) {
                    $file->delete();
                    $this->redirect(array('controller' => 'Subjects', 'action' => 'edit', $id));
                }
            }
        }
    }

    function adjectivelist($adjective_ids) {
        $adjectives = '';
        $adj_ids = explode(',', $adjective_ids);

        $i = 0;
        foreach ($adj_ids as $id) {
            $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id' => $id)));

            $adjectives[$i]['id'] = $adj['Adjective']['id'];
            $adjectives[$i]['name'] = $adj['Adjective']['title'];
            $i++;
        }

        //$adjectivelist = substr($adjectives, 1);
        return $adjectives;
    }

    function synonymlist($id) {
        if ($id) {
            $data = $this->Subject->find('all', array('conditions' => array('Subject.subject_id' => $id), 'fields' => array('Subject.subject', 'Subject.id')));
            //debug($data);
            $synonym_data = array();

            $i = 0;
            foreach ($data as $subject) {
                $synonym_data[$i]['id'] = $subject['Subject']['id'];
                $synonym_data[$i]['name'] = $subject['Subject']['subject'];
                $i++;
            }
            return $synonym_data;
        }
    }

    function admin_attributes($id=null) {
        $this->layout = 'Ajax';
        /*         * ******** Initialize all variables here********* */


        /*         * *************Initialization Ends*************** */

        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            //$this->autoRender = false;
            //$this->layout='Ajax';

            $id = $_REQUEST['id'];
            $old_attrib_num = $_POST['num'];      //Number of Attribute fields already in the form.
            if ($old_attrib_num == '0') {
                $n = 0;
            } else {
                $n = ceil($old_attrib_num / 3) + 1;
            }
            $metadata = array('n' => $n, 'id' => $id);
            $data = $this->Tag->find('all', array('conditions' => array('Tag.parent_id =' => $id, 'Tag.type =' => 'attribute')));
            $this->set('attributes', $data);
            $this->set('meta', $metadata);


            //$this->render('/elements/admin_attributes');
        }
    }

    function formated_attributes($attributes, $i) {

        $result = "<div class='inputattributes'><div style='float:left; padding-right:10px;'>" . $attributes['Tag']['title'] . "</div>
                <div >
                <input id='Attribute" . $i . "attribute' type='hidden' name='data[Attribute][$i][attribute]' value='" . $attributes['Tag']['title'] . "'/>
                " . $this->Form->input('Attribute' . $i . 'value') . "</div></div><br><div style='clear:both;height:10px;'></div>";
        return $result;
    }

    /*     * ********************  This Function will ruturn the search result for subjects    ********************* */

    function admin_search() {

        $data = $this->paginate('Subject', array('OR' => array(array('Subject.desc =' => $this->data['Subject']['search']), array('Subject.subject =' => $this->data['Subject']['search']))));
        $adjectives = '';
        $taglist = '';
        $i = 0;

        /*         * ********  Loop through the fetched data to get Formated Taglist and Adjectives      ****** */

        foreach ($data as $value) {
            $adj_ids = explode(',', $value['Subject']['adjective_ids']);
            $tag_ids = explode(',', $value['Subject']['tag_ids']);

            /*             * ************************* This loop will get you the Adjectives from adjective_ids     ************************ */
            foreach ($adj_ids as $id) {
                $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id =' => $id)));
                $adjectives = $adjectives . ',' . $adj['Adjective']['title'];
            }


            /*             * ************** 
             * This loop will get all the formated tags for a particular record.
             *  Functions used : 
             *                  get_parent_list($tid):accepts tag_id as input. this will return an array with parent ids and parent titles.
             *                  formated_tags($tag_arr,$saparator):First argument is the tag_array returned from get_parent_list.Second parameter is optional. This will be used as to format taglist.
             * 
             * *************** */
            foreach ($tag_ids as $tid) {
                $tag_arr = $this->get_parent_list($tid);
                $taglist = $this->formated_tags($tag_arr, '>');
            }
            $data[$i]['Subject']['adjective_ids'] = substr($adjectives, 1);
            $data[$i]['Subject']['tag_ids'] = $taglist;
            $i++;
            $adjectives = '';
            //$tags='';
        }

        /*         * **********  Loop to get Taglist and Adjectives ENDS     ******************** */

        //debug($data);
        $this->set('Subjects', $data);
    }

    /*     * ******************** This function  is used in autocomplete for search in subject   ******************* */

    function admin_search_suggestion() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject LIKE' => $_GET['q'] . '%')));
            if (empty($subjects)) {
                $subjects = $this->Subject->find('all', array('conditions' => array('Subject.desc LIKE' => $_GET['q'] . '%')));
            }
            $i = 0;
            foreach ($subjects as $subject) {
                $response[$i]['id'] = $subject['Subject']['subject'];
                $response[$i]['name'] = "" . $subject['Subject']['subject'] . "(" . $subject['Subject']['desc'] . ")";
                $i++;
            }
            if (isset($_GET["callback"])) {
                $response = $_GET["callback"] . "(" . $response . ")";
            }

            $response = json_encode($response);
            echo $response;
        }
    }

    function admin_subject_suggestion() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $title = $_GET['title'];
            $specifier = $_GET['specifier'];
            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject' => $title, 'Subject.desc' => $specifier)));

            if ($subjects) {
                return true;
            } else {
                return false;
            }
        }
    }

    function check_image_extension($ext) {
        $response = false;
        $allowedext = array('jpg', 'JPG', 'jpeg', 'JPEG', 'pjpeg', 'png', 'PNG');
        foreach ($allowedext as $extension) {
            if ($extension == $ext) {
                $response = true;
                break;
            }
        }
        return $response;
    }

    function admin_tag() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $response = array();
            $id = '';
            $this->autoRender = false;
            $ids = array_reverse($this->get_parent_list($_POST['id']));
            // print_r($ids);
            foreach ($ids as $value) {
                $id = $id . $value['id'] . ',';
            }
            echo $id . $_POST['id'] . ',0';


            //echo '206,243,205,0';
            $response = json_encode($response);
            //echo $response;
        }
    }

    function admin_update() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $response = array();
            $id = '';
            $this->autoRender = false;
            if (!empty($_POST['id'])) {
                //$query=mysql_query('UPDATE ');

                $this->Subject->id = $_POST['id'];
                $this->data['Subject']['status'] = $_POST['status'];
                $this->Subject->save($this->data);
            }
        }
    }

    function admin_report() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            if (!empty($_POST['id'])) {
                //$query=mysql_query('UPDATE ');
                $query = mysql_query("INSERT INTO `flagged_subjects` (`subject_id`,`user_id`,`type`,`comment`,`created`,`modified`)
                                                VALUES('" . $_POST['subject_id'] . "','" . $_POST['id'] . "','" . $_POST['type'] . "','" . $_POST['comment'] . "',now(),now())
                                   ");
                echo "<div class='thanks'>Thanks for reporting</div>";
            }
        }
    }

    function saveCredit($data) {
        $p = 0;

        $balance = $this->balance($data['User']['id']);

        foreach ($data['Subject'] as $key => $value) {
            if ($value == '1') {
                $point = $this->Credit->find('first', array('conditions' => array('Credit.id' => $key)));

                $this->data['UserCredit'][$p]['credit'] = $point['Credit']['point'];
                $this->data['UserCredit'][$p]['credit_id'] = $key;
                $this->data['UserCredit'][$p]['user_id'] = $data['User']['id'];
                $this->data['UserCredit'][$p]['subject_id'] = $data['Subject']['id'];

                $this->data['UserCredit'][$p]['balance'] = $balance + $this->data['UserCredit'][$p]['credit'];
                //$this->UserCredit->save($this->data['UserCredit']);
                $balance = $this->data['UserCredit'][$p]['balance'];
                $p++;
            }
        }
        if (!empty($this->data['UserCredit'])) {
            $this->UserCredit->saveAll($this->data['UserCredit']);
        }
    }

    function balance($id) {
        $points = $this->Subject->query("SELECT SUM(user_credits.credit) as balance FROM `user_credits` where user_id='$id'");
        return @$points[0][0]['balance'];
    }

    /*     * ***************  This function will set the current edited subject as a base subject for the selected  Subject synonyms. It takes $this->data as parameter********************** */

    function set_base_subject($data) {
        $subject_ids = explode(',', $this->data['Subject']['subject_ids']);
        $old_subject_ids = explode(',', $this->data['Subject']['old_subject_ids']);

        $deletedsyn = array_diff($old_subject_ids, $subject_ids);
        // debug($subject_ids);
        //debug($data);die();
        foreach ($deletedsyn as $id) {
            $update_subject_id = $this->Subject->query("UPDATE `subject` set `subject_id`='0' WHERE `id`='" . $id . "'");
        }
        foreach ($subject_ids as $subject_id)
            $update_subject_id = $this->Subject->query("UPDATE `subject` set `subject_id`='" . $this->data['Subject']['id'] . "' WHERE `id`='" . $subject_id . "'");
        return true;
    }

    function initialize_curl($response,$search, $offset, $i,$subjectlist) {
        //print_r($subjectlist);
        $useragent = env('HTTP_USER_AGENT');
        $url = "http://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" . $_GET['search'] . "&srprop=hasrelated&srlimit=50&sroffset=" . $offset . "&format=json&what=title";
        $ch = curl_init($url);

// set user agent
        curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
//$ch = curl_init ($url) ;
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = json_decode(curl_exec($ch));
        curl_close($ch);
       //print_r($res);
        foreach ($res->query->search as $subject) {
            if (!in_array($subject->title, $subjectlist) && !in_array($subject->title,$response)) {
                $response[$i]['id'] = $subject->title;
                $response[$i]['name'] = $subject->title;
                $i++;
            }
            if ($i == '50') {
                    break;
                } 
        }
        //echo $i."<br>";
        if($i<'50'){
        return $this->initialize_curl($response,$search,50+$offset,$i,$subjectlist);
        }else{
        return $response;
        }
        //return $response;
    }

    function check() {
        echo phpinfo();
    }

}

?>
